<template>
  <a-menu
      v-model:selectedKeys="selectedKeys"
      style="width: 100%;height:calc(100vh - 62px);"
      mode="inline"
      selectable
      theme="dark"
      @click="handleClick"
  >
    <a-menu-item key="/home">
      <template #icon>
        <MailOutlined/>
      </template>
      首页
    </a-menu-item>
    <a-menu-item key="/dict" v-if="isJurisdiction('数据字典')">
      <template #icon>
        <CalendarOutlined/>
      </template>
      数据字典
    </a-menu-item>
    <a-menu-item key="/user" v-if="isJurisdiction('用户管理')">
      <template #icon>
        <UserOutlined/>
      </template>
      用戶管理
    </a-menu-item>

    <a-sub-menu v-for="item in menuRequest" :key="item.key">
      <template #icon>
        <AreaChartOutlined/>
      </template>
      <template #title>{{ item.name }}</template>
      <a-menu-item v-for="childItems in item.child" :key="childItems.key">{{ childItems.name }}</a-menu-item>
    </a-sub-menu>

  </a-menu>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, toRefs, watchEffect} from 'vue';
import {
  MailOutlined,
  CalendarOutlined,
  UserOutlined,
  AreaChartOutlined
} from '@ant-design/icons-vue';
import type {MenuProps} from "ant-design-vue";
import {useRoute, useRouter} from "vue-router";
import type {DictCategoryType} from "@/util/publicType";
import {useDictCategory} from "@/Hooks";
import {InfoType} from "@/util/publicType";
import {info} from "@/api/api";
import {message} from "ant-design-vue";

// 默认选择项
const state = reactive({
  selectedKeys: ['/home'],
});

// menu动态列表
const menuRequest = ref<DictCategoryType[]>([]);

// 路由
const router = useRouter();

// 路由信息
const routes = useRoute();

// 自定义hook
const {menuData} = useDictCategory();

// 信息数据
const infoData = ref<InfoType>({
  id: "",
  jurisdictions: [],
  created_at: 0,
  lasted_at: 0,
  username: ""
});

// 切换菜单
const handleClick: MenuProps['onClick'] = menuInfo => {
  router.push(menuInfo.key as string);
}

// 异步数据全局状态监听不到,再次书写info接口
onMounted(async () => {
  try {
    const r = await info();
    infoData.value = r.data.data.data;
  } catch (err) {
    message.error(err as string)
  }
})

// 是否拥有权限
const isJurisdiction = (name: string) => infoData.value.jurisdictions.findIndex(v => v.name === name) >= 0

// 根据地址选择key
watchEffect(() => {
  // 获取key
  state.selectedKeys = [routes.path];
  let data = menuData.value.map((v: DictCategoryType) => {
    let key: string = '';
    switch (v.name) {
      case '文献管理':
        key = '/literature'
        break;
      case '文章管理':
        key = '/article'
        break;
      default:
        key = '/region'
        break;
    }
    v.child = v.child?.map(v => {
      return {
        ...v,
        key: key + '/' + v.id
      }
    })
    return {
      ...v,
      key,
    }
  });
  menuRequest.value = data;
});


const {selectedKeys} = toRefs(state);
</script>
<style scoped lang="less">

</style>